<template>
  <div id="edit-shop">
    <div class='form-content' v-show="isShow">
      <RadioGroup v-model="btnValue" type="button" style="margin: 30px 0" @on-change='onChange'>
        <Radio label="1">门店基础信息</Radio>
        <Radio label="2">门店标签管理</Radio>
        <Radio label="3">业务及其他</Radio>
      </RadioGroup>
      <Form ref="formInline" v-show="btnValue === '1'"
            :model="formInline"
            :rules="ruleInline"
            :label-width="110">
        <!-- <h3>门店基础信息</h3> -->
        <FormItem prop="shopName"
                  label="门店名称：" class='form-content-top'>
          <Input type="text"
                  v-model="formInline.shopName"
                  :disabled="disabled"
                  style="width:280px"
                  placeholder="门店名称"></Input>
        </FormItem>
        <FormItem prop="shopCode"
                  label="门店编码：">
          <Input type="text"
                  v-model="formInline.shopCode"
                  @on-keyup="filterSpace"
                  :disabled="disabledCode"
                  :maxlength="20"
                  placeholder="请输入门店编号"
                  style="width:280px"></Input>
        </FormItem>
        <!-- </FormItem> -->
        <!-- <FormItem label="所在地区："
                  prop="province"> -->
        <Row type="flex"
              justify="start">
          <!-- <Col :span="6"> -->
          <FormItem label="所在地区："
                    prop="province">
            <Select v-model="formInline.province"
                    style="width:100px;"
                    @on-change="selctProvince">
              <Option v-for="(item,index) in provinceList"
                      v-if="item"
                      :value="index"
                      :key="item">{{ item }}</Option>
            </Select>
          </FormItem>
          </Col>
          <!-- <Col :span="6"
                offset="2"> -->
          <FormItem prop="city"
                    class="cityfoem">
            <Select v-model="formInline.city"
                    style="width:100px;"
                    @on-change="selctCity">
              <Option v-for="(item,index) in cityList"
                      v-if="item"
                      :value="index"
                      :key="item">{{item}}</Option>
            </Select>
          </FormItem>
          <!-- </Col> -->
          <!-- <Col :span="6"
                offset="2"> -->
          <FormItem prop="area"
                    class="cityfoem">
            <Select v-model="formInline.area"
                    style="width:100px;"
                    @on-change="selctArea">
              <Option v-for="item in areaList"
                      :value="item"
                      :key="item">{{item}}</Option>
            </Select>
          </FormItem>
          </Col>
        </Row>
        <!-- </FormItem> -->
        <FormItem prop="address"
                  label="详细地址：">
          <Input type="text"
                  v-model="formInline.address"
                  :maxlength="100"
                  placeholder="请输入详细地址"
                  style="width:280px"
                  search
                  @on-search="keydownAddress"></Input>
        </FormItem>
        <div class="baiduMap">
          <baidu-map class="bm-view"
                      ak="scRvm7dsu17R5Dg1XjC79F9634GvzUVQ"
                      :center="center"
                      :zoom="15"
                      :scroll-wheel-zoom="true"
                      @ready="ready"
                      v-if="mapIStrue">
            <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
            <bm-navigation anchor="BMAP_ANCHOR_TOP_LEFT"></bm-navigation>
            <bm-overview-map anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
                              :isOpen="true"></bm-overview-map>
            <bm-local-search :keyword="keyword"
                              :panel="false"
                              :pageCapacity="1"
                              @searchcomplete="searchComplete"
                              :selectFirstResult="true"></bm-local-search>
            <bm-marker :position="autoLocationPoint"
                        v-if="initLocation">
            </bm-marker>
          </baidu-map>
        </div>
        <!-- <h3>门店服务信息</h3> -->
        <FormItem prop="contracts"
                  label="联系人："
                  class="form-content-top">
          <Input type="text"
                  v-model="formInline.contracts"
                  :maxlength="20"
                  @on-keyup="filterSpaceContracts"
                  placeholder="请输入联系人"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem prop="telephone"
                  label="联系电话：">
          <Input type="text"
                  v-model="formInline.telephone"
                  @on-keyup="filterTel"
                  @on-blur="filtertelephone"
                  :maxlength="20"
                  placeholder="请输入联系电话"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem prop="peopleConsumption"
                  label="人均消费：">
          <Input v-model="formInline.peopleConsumption"
                  :maxlength="13"
                  @on-keyup="changeprice"
                  @on-blur="changeblur"
                  placeholder="请输入人均消费金额"
                  style="width:280px"></Input>
          <span style="margin-left:20px;">元</span>
        </FormItem>
        <FormItem prop="businessHours"
                  label="营业时间：">
          <TimePicker v-model="formInline.businessHours"
                      @on-change="selectChange"
                      :editable="false"
                      format="HH:mm"
                      type="timerange"
                      placement="bottom-end"
                      placeholder="如:10:00-21:00"
                      style="width: 280px"></TimePicker>
        </FormItem>
        <FormItem prop="spelling"
                  label="简拼：">
          <Input type="text"
                  v-model="formInline.spelling"
                  :maxlength="20"
                  @on-keyup="filterSpaceSpelling"
                  placeholder="请输入简拼"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem prop="shopProperty"
                  label="门店类型：">
          <Select v-model="formInline.shopProperty"
                  @on-change="selectproperty"
                  style="width:280px">
            <Option v-for="(item, i) in typeList" :key='i' :value='item'>{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem prop="postCode"
                  label="邮箱：">
          <Input type="text"
                  :maxlength="40"
                  v-model="formInline.postCode"
                  @on-keyup="filterPostCode"
                  placeholder="请输入邮箱地址"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem prop="fax"
                  label="传真号码：">
          <Input type="text"
                  v-model="formInline.fax"
                  :maxlength="20"
                  placeholder="请输入传真密码"
                  @on-keyup="filterFax"
                  @on-blur="blurfax"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem prop="authorizedPassword"
                  label="授权密码：">
          <Input type="text"
                  v-model="formInline.authorizedPassword"
                  :maxlength="40"
                  @on-keyup="filterSpacePassword"
                  :disabled="authpwdDisabled"
                  placeholder="请输入授权密码"
                  style="width:280px"></Input>
        </FormItem>
        <FormItem label="特色推荐："
                  prop="characteristic"
                  style='width:100%;margin-bottom:0'
                  class="characteristic">
          <Input v-model="formInline.characteristic"
                  type="textarea"
                  style="width:280px"
                  :maxlength="200"
                  class="characteristic"
                  :autosize="{minRows: 4,maxRows: 6}"
                  placeholder="如：跳舞机、投篮机"></Input>
                  <p class="tip-count">{{formInline.characteristic?formInline.characteristic.length:0}}/300</p>
        </FormItem>
        <FormItem label="店面营销标签："
                  prop="marketingLabel"
                  style='width:100%;margin-bottom:0'
                  class="characteristic">
          <Input v-model="formInline.marketingLabel"
                  placeholder="填写标签值，如电玩、娱乐"
                  type="textarea"
                  style="width:280px"
                  :maxlength="200"
                  :autosize="{minRows: 4,maxRows: 6}"></Input>
                  <p class="tip-count">{{formInline.marketingLabel?formInline.marketingLabel.length:0}}/300</p>
        </FormItem>
        <FormItem label="门店介绍："
                  prop="shopIntroduce"
                  class="characteristic"
                  style='width:100%;margin-bottom:0'>
          <Input v-model="formInline.shopIntroduce"
                  placeholder="对门店的简要介绍"
                  type="textarea"
                  style="width:280px"
                  :maxlength="500"
                  :autosize="{minRows: 4,maxRows: 6}"></Input>
                  <p class="tip-count">{{formInline.shopIntroduce?formInline.shopIntroduce.length:0}}/300</p>
        </FormItem>
        <FormItem label="门店图片："
                  prop="shopImage"
                  style='width:100%'>
          <Upload ref="upload"
                  :format="['jpg','png']"
                  :max-size="100"
                  :on-success="handleSuccess"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  type="drag"
                  :show-upload-list="false"
                  :action="$config.uploadImg"
                  style="display: inline-block;width:96px;">
            <img :src="formInline.shopImage?formInline.shopImage:defaultUrl"
                  style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                  alt="">
            <p v-if="formInline.shopImage"
                class="replace_tit"
                @click.stop="removeshopImage">删除</p>
          </Upload>
          <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;display:inline-block;vertical-align: top;">支持格式：.jpg、.png；规格：320*256；大小：≤100K</div>
        </FormItem>
        <FormItem style='width:100%'>
          <Button type="primary"
                  @click="submitForm">确定</Button>
          <Button style="margin-left: 8px"
                  @click="replacement">取消</Button>
        </FormItem>
      </Form>
      <Form inline v-show="btnValue === '2'" :label-width="110" ref="formValidate" :model="formValidate" :rules="ruleValidate">
        <FormItem label='状态：' prop='status' style="display: block;" class='form-content-top'>
          <Select style="width:280px" v-model='formValidate.status'>
            <Option v-for='(item,i) in statusList' :key='i' :value='item'>{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem label='品牌：' prop='brandId'>
          <Select style="width:280px" v-model='formValidate.brandId'>
            <Option v-for='(item,i) in brandList' :key='i' :value='item.brandId'>{{item.brandName}}</Option>
          </Select>
        </FormItem>
        <FormItem label='等级：' prop='shopLevel' :label-width="150">
          <Select style="width:280px" v-model='formValidate.shopLevel'>
            <Option v-for='(item,i) in levelList' :key='i' :value='item'>{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem label='项目类型：' prop='projectType'>
          <Select style="width:280px" v-model='formValidate.projectType'>
            <Option v-for='(item,i) in itemTypeList' :key='i' :value='item'>{{item}}</Option>
          </Select>
        </FormItem>
        <FormItem label='项目名称：' prop='projectName' :label-width="150">
          <Input type="text" style="width: 280px;" v-model="formValidate.projectName" placeholder="请输入" :maxlength="48" @on-keyup='filterName' @on-blur="filterName"></Input>
        </FormItem>
        <FormItem label='开业年份：' prop='openingYear'>
          <DatePicker type="year" placement="bottom-end" format="yyyy" placeholder="请选择" style="width:280px" :value='formValidate.openingYear' @on-change='chageOpenYear'></DatePicker>
        </FormItem>
        <FormItem label='开业/接管日期：' prop='openingTime' :label-width="150">
          <DatePicker type="datetime" placement="bottom-end" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择" style="width:280px" :value='formValidate.openingTime' @on-change='chageOpenDate'></DatePicker>
        </FormItem>
        <FormItem style='width:100%'>
          <Button type="primary" @click="submitForm2">确定</Button>
          <Button style="margin-left: 8px" @click="replacement">取消</Button>
        </FormItem>
      </Form>
      <Form inline v-show="btnValue === '3'" :label-width="110" ref="formCustom" :model="formCustom" :rules="ruleCustom">
        <FormItem label='业务标签选择：' prop='relationlist' style="display: block;" class='form-content-top'>
          <treeselect class="list_treeselect" :limit='1' :limitText='limitText'
                      style="width:280px;"
                      :multiple="true"
                      v-model='formCustom.relationlist'
                      noResultsText="未搜索符合的标签"
                      :options="options"
                      :normalizer="normalizer"
                      :value-consists-of="valueConsistsOf"
                      placeholder="请选择" />
        </FormItem>
        <FormItem label='营业面积：' prop='businessArea'>
          <Input type="text" style="width: 280px;" v-model="formCustom.businessArea" placeholder="请输入0.01-99999.99，单位平方米" :maxlength="8" @on-keyup="changeNum('businessArea')" @on-blur="changeNum('businessArea')"></Input>
        </FormItem>
        <FormItem label='每月租金：' prop='rental'>
          <Input type="text" style="width: 280px;" v-model="formCustom.rental" placeholder="请输入0.01-9999999.99 单位元，含租物业费" :maxlength="10" @on-keyup="changeNum('rental')" @on-blur="changeNum('rental')"></Input>
        </FormItem>
        <FormItem label='基准电费：' prop='powerRate'>
          <Input type="text" style="width: 280px;" v-model="formCustom.powerRate" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('powerRate')" @on-blur="changeNum('powerRate')"></Input>
        </FormItem>
        <FormItem label='人员成本：' prop='personnelCost'>
          <Input type="text" style="width: 280px;" v-model="formCustom.personnelCost" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('personnelCost')" @on-blur="changeNum('personnelCost')"></Input>
        </FormItem>
        <FormItem label='礼品成本：' prop='giftCost'>
          <Input type="text" style="width: 280px;" v-model="formCustom.giftCost" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('giftCost')" @on-blur="changeNum('giftCost')"></Input>
        </FormItem>
        <FormItem label='其他成本：' prop='otherCost'>
          <Input type="text" style="width: 280px;" v-model="formCustom.otherCost" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('otherCost')" @on-blur="changeNum('otherCost')"></Input>
        </FormItem>
        <FormItem label='销售指标：' prop='salesTarget'>
          <Input type="text" style="width: 280px;" v-model="formCustom.salesTarget" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('salesTarget')" @on-blur="changeNum('salesTarget')"></Input>
        </FormItem>
        <FormItem label='利润指标：' prop='profitTarget'>
          <Input type="text" style="width: 280px;" v-model="formCustom.profitTarget" placeholder="请输入0.01-9999999.99 单位元/月" :maxlength="10" @on-keyup="changeNum('profitTarget')" @on-blur="changeNum('profitTarget')"></Input>
        </FormItem>
        <FormItem style='width:100%'>
          <Button type="primary" @click="submitForm3">确定</Button>
          <Button style="margin-left: 8px" @click="replacement">取消</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { brandList, tagTree } from '@/api/system/tag'
import { area_array, sub_array, sub_arr } from '@/libs/area-data'
import { BaiduMap, BmNavigation, BmScale, BmGeolocation, BmMarker, BmLocalSearch, BmOverviewMap } from 'vue-baidu-map'
import { lookShopInfos, updateShopInfos, getDicQuery } from '@/api/setting'
import { routeEqual } from '@/libs/util'
export default {
  name: 'store_edit',
  components: {
    BaiduMap, BmNavigation, BmScale, BmGeolocation, BmMarker, BmLocalSearch, BmOverviewMap, Treeselect
  },
  data () {
    return {
      valueConsistsOf: 'ALL',
      options: [],
      normalizer (node) {
        if (node.shopTags) {
          if (node.shopTags.length > 0) {
            return {
              id: node.shopTagId,
              label: node.shopTagName,
              children: node.shopTags
            }
          } else {
            return {
              id: node.shopTagId,
              label: node.shopTagName,
              isDisabled: node.level === 2 ? '' : true
            }
          }
        }
      },
      formCustom: {
        relationlist: null,
        businessArea: '',
        rental: '',
        powerRate: '',
        personnelCost: '',
        giftCost: '',
        otherCost: '',
        salesTarget: '',
        profitTarget: ''
      },
      ruleCustom: {},
      typeList: [],
      statusList: [],
      brandList: [],
      levelList: [],
      itemTypeList: [],
      formValidate: {
        status: '',
        brandId: '',
        shopLevel: '',
        projectType: '',
        projectName: '',
        openingYear: '',
        openingTime: ''
      },
      ruleValidate: {
        status: { required: true, message: '请选择状态', trigger: 'change' },
        brandId: { required: true, message: '请选择品牌', trigger: 'change' },
        shopLevel: { required: true, message: '请选择等级', trigger: 'change' },
        projectType: { required: true, message: '请选择项目类型', trigger: 'change' },
        projectName: { required: true, message: '请输入项目名称', trigger: 'blur' },
        openingYear: { required: true, message: '请选择开业年份', trigger: 'blur' },
        openingTime: { required: true, message: '请选择开业/接管日期', trigger: 'blur' }
      },
      btnValue: '1',
      provinceArr: [],
      isShow: false,
      cityArr: [],
      mapIStrue: false,
      defaultUrl: require('@/assets/images/default.png'),
      areaArr: [],
      ischaracteristic: false,
      provinceList: [],
      location: '',
      disabledCode: false,
      keyword: '',
      routerId: '',
      cityList: [],
      imgUrl: '',
      pcaa: [],
      isUpload: true,
      areaList: [],
      saveCenter: { lng: 0, lat: 0 },
      center: { lng: 0, lat: 0 },
      autoLocationPoint: { lng: 0, lat: 0 },
      initLocation: false,
      disabled: true,
      formInline: {
        merchantId: this.$store.state.user.merchantId, // 商户id
        shopId: this.$route.params.id, // 门店id
        shopName: '', // 门店名称
        shopCode: '', // 门店code
        province: null, // 省
        city: null, // 市
        area: null, // 地区
        address: '', // 门店地址
        contracts: '', // 店面负责人
        telephone: '', // 座机号码
        peopleConsumption: '', // 人均消费
        businessHours: '', // 营业时间
        shopProperty: '-1', // 门店性质 0直营 1非直营 2加盟
        spelling: '', // 简拼
        postCode: '', // 邮编
        fax: '', // 传真号码
        authorizedPassword: '', // 授权密码
        characteristic: '', // 特色推荐
        marketingLabel: '', // 店面营销标签
        shopIntroduce: '', // 门店介绍
        longitude: '', // 经度
        latitude: '', // 纬度
        shopImage: '' // 门店图片
      },
      authpwdDisabled: false,
      defaultList: [
      ],
      imgName: '',
      visible: false,
      uploadList: [],
      ruleInline: {
        shopName: [{
          required: true, message: '门店名称不能为空', trigger: 'blur'
        }],
        shopCode: [{
          required: true, min: 1, message: '请输入门店编号', trigger: 'blur'
        }, {
          required: true, message: '最多可输入100字', max: 100, trigger: 'blur'
        }],
        province: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请选择省份'))
            } else {
              callback()
            }
          }
        }],
        city: [{
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请选择城市'))
            } else {
              callback()
            }
          }
        }],
        area: [{
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value === '请选择') {
              callback(new Error('请选择区域'))
            } else if (!value) {
              callback(new Error('请选择区域'))
            } else {
              callback()
            }
          }
        }],
        address: [{
          required: true, message: '请输入详情地址', trigger: 'blur'
        }],
        contracts: [{
          required: true, message: '请输入联系人', trigger: 'blur'
        }],
        telephone: [{
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入联系电话'))
            }
            callback()
          }
        }],
        peopleConsumption: [{
          required: true, message: '请输入人均消费金额', trigger: 'blur'
        }, {
          required: true, message: '请输入正确金额', trigger: 'blur', pattern: /^[1-9][0-9]{0,11}(\.\d{1,2})?$/
        }],
        businessHours: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value[0] === '' || !value) {
              callback(new Error('请输入营业时间,如10:00-21:00'))
            } else {
              callback()
            }
          }
        }],
        shopProperty: [{
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value === '-1') {
              callback(new Error('请选择门店性质'))
            } else {
              callback()
            }
          }
        }],
        postCode: [{
          message: '邮箱格式不正确', trigger: 'blur', pattern: /^[A-Za-z\d]+([A-Za-z\d]+)*@([A-Za-z\d]+[.])+[A-Za-z\d]{2,4}$/
        }],
        fax: [{
          required: true, message: '请输入传真号码', trigger: 'blur'
        }]
      }
    }
  },
  created () {
    this.provinceList = area_array
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.routerId !== to.params.id) {
        vm.formInline.province = ''
        vm.formInline.city = ''
        vm.formInline.area = ''
        vm.routerId = to.params.id
        vm.isShow = false
        lookShopInfos({
          merchantId: vm.$store.state.user.merchantId,
          shopId: to.params.id
        }).then((res) => {
          if (res.data.status === 200) {
            vm.$refs.formInline.resetFields()
            setTimeout(() => {
              vm.isShow = true
            }, 500)
            vm.authpwdDisabled = !!res.data.data.authorizedPassword
            vm.formInline = res.data.data
            vm.formInline.shopId = to.params.id
            vm.formInline.businessHours = res.data.data.businessHours ? res.data.data.businessHours.split('-') : ''
            vm.formInline.province = Number(res.data.data.province)
            vm.formInline.shopProperty = res.data.data.shopProperty === null ? '-1' : res.data.data.shopProperty
            vm.formInline.peopleConsumption = res.data.data.peopleConsumption ? res.data.data.peopleConsumption : ''
            if (res.data.data.shopCode) {
              vm.disabledCode = true
              vm.formInline.shopCode = res.data.data.shopCode
            } else {
              vm.disabledCode = false
              vm.formInline.shopCode = ''
            }
            vm.formInline.city = Number(res.data.data.city)
            vm.formInline.fax = res.data.data.fax ? String(res.data.data.fax) : ''
            vm.formInline.peopleConsumption = res.data.data.peopleConsumption + ''
            vm.imgUrl = res.data.data.shopImage
            vm.cityList = sub_array[vm.formInline.province]
            vm.areaList = []
            for (var p in sub_arr[vm.formInline.city]) {
              vm.areaList.push(sub_arr[vm.formInline.city][p])
            }
            var geolocation = new BMap.Geolocation()
            geolocation.getCurrentPosition((r) => {
              vm.saveCenter = { lng: r.longitude, lat: r.latitude }
              vm.center.lng = vm.formInline.longitude ? vm.formInline.longitude : r.longitude
              vm.center.lat = vm.formInline.latitude ? vm.formInline.latitude : r.latitude
            }, { enableHighAccuracy: true })
            vm.keyword = area_array[vm.formInline.province] + sub_array[vm.formInline.province][vm.formInline.city] + vm.formInline.area + vm.formInline.address
            vm.formInline.province = res.data.data.province ? Number(res.data.data.province) : ''
            vm.formInline.city = res.data.data.city ? Number(res.data.data.city) : ''
            vm.formInline.area = res.data.data.area ? res.data.data.area : ''
            vm.mapIStrue = true
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      }
    })
  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
    this.routerId = this.$route.params.id
    this.$refs.formInline.resetFields()
    this.getStoreType()
    this.getShopInfo()
  },
  methods: {
    filterName () {
      this.formValidate.projectName = this.formValidate.projectName.replace(/[^A-Za-z\u4e00-\u9fa5]/, '')
    },
    chageOpenYear (time) {
      this.formValidate.openingYear = time
    },
    chageOpenDate (time) {
      this.formValidate.openingTime = time
    },
    submitForm3 () {
      this.$refs.formCustom.validate(valid => {
        if (valid) {
          let data = { ...this.formCustom, merchantId: this.$store.state.user.merchantId, shopId: this.$route.params.id }
          if (data.relationlist) {
            data.relationlist = data.relationlist.map(item => {
              return {
                shopId: this.$route.params.id,
                shopTagId: item
              }
            })
          }
          this.handleSubmit(data)
        }
      })
    },
    submitForm2 () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          let data = { ...this.formValidate, openingYear: this.formValidate.openingYear + '-01-01 00:00:00', merchantId: this.$store.state.user.merchantId, shopId: this.$route.params.id }
          this.handleSubmit(data)
        }
      })
    },
    onChange () {
      if (this.btnValue === '3') {
        this.getTag()
      } else {
        if (this.btnValue === '2') {
          this.getBrand()
        }
        this.getStoreType()
      }
    },
    // 获取品牌
    getBrand () {
      brandList({ merchantId: this.$store.state.user.merchantId }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.brandList = result.data || []
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取类型、状态
    getStoreType () {
      getDicQuery({
        dictKeys: 'shopType,shopStatus,shopLevel,projectType',
        merchantId: this.$store.state.user.merchantId,
        msType: '0'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          if (result.data[0].shopType + '' !== '0') {
            this.typeList = result.data[0].shopType.split('|') || []
          }
          if (result.data[1].shopStatus + '' !== '0') {
            this.statusList = result.data[1].shopStatus.split('|') || []
          }
          if (result.data[2].shopLevel + '' !== '0') {
            this.levelList = result.data[2].shopLevel.split('|') || []
          }
          if (result.data[3].projectType + '' !== '0') {
            this.itemTypeList = result.data[3].projectType.split('|') || []
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    // 获取业务标签
    getTag () {
      tagTree({ tagStatus: '1', level: 1, merchantId: this.$store.state.user.merchantId }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.options = result.data
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    limitText () {
      return '...'
    },
    changeNum (data) {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (
        this.formCustom[data] !== '' &&
        this.formCustom[data].substring(0, 1) === '.'
      ) {
        this.formCustom[data] = ''
      }
      this.formCustom[data] = this.formCustom[data].replace(
        /^0*(0\.|[1-9])/,
        '$1'
      ) // 粘贴不生效
      this.formCustom[data] = this.formCustom[data].replace(
        /[^\d.]/g,
        ''
      ) // 清除“数字”和“.”以外的字符
      this.formCustom[data] = this.formCustom[data].replace(
        /\.{2,}/g,
        '.'
      ) // 只保留第一个. 清除多余的
      this.formCustom[data] = this.formCustom[data]
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      this.formCustom[data] = this.formCustom[data].replace(
        /^(-)*(\d+)\.(\d\d).*$/,
        '$1$2.$3'
      ) // 只能输入两个小数
      if (
        this.formCustom[data].indexOf('.') < 0 &&
        this.formCustom[data] !== ''
      ) {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (
          this.formCustom[data].substring(0, 1) === '0' &&
          this.formCustom[data].length === 2
        ) {
          this.formCustom[data] = this.formCustom[data].substring(
            1,
            this.formCustom[data].length
          )
        }
      }
      if (data === 'businessArea') {
        if (this.formCustom[data] > 99999.99) {
          this.formCustom[data] = this.formCustom[data].substring(0, 5)
        }
      } else {
        if (this.formCustom[data] > 9999999.99) {
          this.formCustom[data] = this.formCustom[data].substring(0, 7)
        }
      }
    },
    // 取消
    replacement () {
      this.closeModal()
    },
    // 提交
    submitForm () {
      let businessHours = this.formInline.businessHours ? this.formInline.businessHours.join('-') : ''
      this.$refs.formInline.validate((valid) => {
        if (valid) {
          let data = { ...this.formInline, businessHours: businessHours }
          this.handleSubmit(data)
        }
      })
    },
    // 编辑接口
    handleSubmit (data) {
      updateShopInfos(data).then(res => {
        if (res.data.status === 200) {
          this.$Message.success('编辑成功')
          this.closeModal()
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getShopInfo () {
      lookShopInfos({
        merchantId: this.$store.state.user.merchantId,
        shopId: this.$route.params.id
      }).then((res) => {
        if (res.data.status === 200) {
          const result = res.data.data || {}
          this.isShow = true
          this.authpwdDisabled = !!res.data.data.authorizedPassword
          this.formInline = res.data.data
          this.formInline.businessHours = res.data.data.businessHours ? res.data.data.businessHours.split('-') : ''
          this.formInline.province = Number(res.data.data.province)
          this.formInline.shopProperty = res.data.data.shopProperty === null ? '-1' : res.data.data.shopProperty
          this.formInline.peopleConsumption = res.data.data.peopleConsumption ? res.data.data.peopleConsumption : ''
          if (res.data.data.shopCode) {
            this.disabledCode = true
            this.formInline.shopCode = res.data.data.shopCode
          } else {
            this.disabledCode = false
            this.formInline.shopCode = ''
          }
          // this.formInline.shopCode = res.data.data.shopCode ? res.data.data.shopCode : ''
          this.formInline.city = Number(res.data.data.city)
          this.formInline.fax = res.data.data.fax ? String(res.data.data.fax) : ''
          this.formInline.peopleConsumption = res.data.data.peopleConsumption + ''
          this.imgUrl = res.data.data.shopImage
          this.cityList = sub_array[this.formInline.province]
          for (var p in sub_arr[this.formInline.city]) {
            this.areaList.push(sub_arr[this.formInline.city][p])
          }
          this.center.lng = this.formInline.longitude
          this.center.lat = this.formInline.latitude
          this.keyword = area_array[this.formInline.province] + sub_array[this.formInline.province][this.formInline.city] + this.formInline.area + this.formInline.address
          this.formInline.province = res.data.data.province ? Number(res.data.data.province) : ''
          this.formInline.city = res.data.data.city ? Number(res.data.data.city) : ''
          this.mapIStrue = true
          // 门店标签管理
          this.formValidate = {
            status: result.status ? result.status : '',
            brandId: result.brandId ? result.brandId : '',
            shopLevel: result.shopLevel ? result.shopLevel : '',
            projectType: result.projectType ? result.projectType : '',
            projectName: result.projectName ? result.projectName : '',
            openingYear: result.openingYear ? result.openingYear : '',
            openingTime: result.openingTime ? result.openingTime : ''
          }
          // 业务及其他
          this.formCustom = {
            relationlist: result.tagIds.length > 0 ? result.tagIds : null,
            businessArea: result.businessArea,
            rental: result.rental,
            powerRate: result.powerRate,
            personnelCost: result.personnelCost,
            giftCost: result.giftCost,
            otherCost: result.otherCost,
            salesTarget: result.salesTarget,
            profitTarget: result.profitTarget
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    filtertelephone () {
      this.formInline.telephone = this.formInline.telephone.replace(/\s/g, '')
      this.formInline.telephone = this.formInline.telephone.replace(/[^0-9-]+/, '')
    },
    changeprice () {
      this.formInline.peopleConsumption = this.formInline.peopleConsumption.replace(/^(0+)|[^\d]+/g, '')
      if (this.formInline.peopleConsumption > 999999999999) {
        this.formInline.peopleConsumption = this.formInline.peopleConsumption.substring(0, 12)
      }
    },
    changeblur () {
      this.formInline.peopleConsumption = this.formInline.peopleConsumption.replace(/[^\d.]/g, '')
      if (this.formInline.peopleConsumption === '') {
        this.formInline.peopleConsumption = ''
      } else if (this.formInline.peopleConsumption.indexOf('.') === -1) {
        this.formInline.peopleConsumption = this.formInline.peopleConsumption + '.00'
      }
    },
    selectproperty (val) {
    },
    filterTel (e) {
      this.formInline.telephone = this.formInline.telephone.replace(/\s/g, '')
      this.formInline.telephone = this.formInline.telephone.replace(/[^0-9-]+/, '')
    },
    removeshopImage () {
      this.formInline.shopImage = ''
    },
    filterFax () {
      this.formInline.fax = this.formInline.fax.replace(/\s/g, '')
      this.formInline.fax = this.formInline.fax.replace(/[^0-9]+/, '')
    },
    blurfax () {
      this.formInline.fax = this.formInline.fax.replace(/[^0-9]+/, '')
    },
    filterPostCode (e) {
      e.target.value = e.target.value.replace(/\s/g, '')
      this.formInline.postCode = e.target.value.replace(/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g, '')
    },
    filterSpace () {
      this.formInline.shopCode = this.formInline.shopCode.replace(/\s/g, '')
      this.formInline.shopCode = this.formInline.shopCode.replace(/[^A-Za-z0-9]/g, '')
    },
    filterSpaceContracts () {
      this.formInline.contracts = this.formInline.contracts ? this.formInline.contracts.replace(/\s/g, '') : ''
    },
    filterSpaceSpelling () {
      this.formInline.spelling = this.formInline.spelling ? this.formInline.spelling.replace(/\s/g, '') : ''
    },
    filterSpacePassword () {
      this.formInline.authorizedPassword = this.formInline.authorizedPassword ? this.formInline.authorizedPassword.replace(/\s/g, '') : ''
    },
    closeModal () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'store_list'
        })
      })
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    // 获取图片尺寸
    getcicun (url) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width !== 320 && img.height !== 256) {
          _this.formInline.shopImage = _this.imgUrl
          _this.$Notice.warning({
            title: '上传的图片规格不符'
          })
        }
      }
    },
    selectChange (value) {
    },
    handleSuccess (response, file, fileList) {
      this.formInline.shopImage = response.full_img_url
      this.getcicun(this.formInline.shopImage)
    },
    // 省
    selctProvince (value) {
      this.$refs.formInline.validateField('province')
      this.cityList = []
      this.areaList = []
      this.formInline.city = ''
      this.formInline.area = ''
      this.keyword = ''
      this.keyword = this.provinceList[value]
      sub_array.forEach((ele, index) => {
        if (value === index) {
          this.cityList = ele
        }
      })
    },
    // 城市
    selctCity (value) {
      this.keyword = ''
      this.keyword = this.keyword + this.cityList[value]
      this.formInline.area = ''
      this.areaList = []
      for (var p in sub_arr[value]) {
        this.areaList.push(sub_arr[value][p])
      }
    },
    // 地区
    selctArea (val) {
      this.keyword = ''
      this.keyword = this.keyword + val
    },
    keydownAddress () {
      this.keyword = this.keyword + this.formInline.address
    },
    searchComplete (e) {
      let Ar = e.Ir
      if (Ar) {
        if (Ar.length) {
          const res = Ar[0]
          this.formInline.longitude = res.point.lng
          this.formInline.latitude = res.point.lat
        }
      }
    },
    ready ({ BMap, map }) {
      let _this = this
      if (!this.formInline.longitude && !this.formInline.latitude) {
        var geolocation = new BMap.Geolocation()
        geolocation.getCurrentPosition(function (r) {
          _this.center = { lng: r.longitude, lat: r.latitude }
          _this.autoLocationPoint = { lng: r.longitude, lat: r.latitude }
          _this.initLocation = true
        }, { enableHighAccuracy: true })
      }
    }
  }
}
</script>

<style lang='less'>
#edit-shop {
  .form-content {
    width: 850px;
    margin-left: 55px;
    .baiduMap {
      width: 430px;
      height: 208.7px;
      margin-left: 110px;
      .bm-view {
        width: 100%;
        height: 100%;
      }
    }
    h3 {
      font-size: 14px;
      line-height: 20px;
      font-weight: normal;
      padding-top: 8px;
      color: #464c5b;
      padding-bottom: 8px;
    }
    .form-content-top {
      margin-top: 32px;
    }
    .tip {
      position: absolute !important;
      left: 0 !important;
      bottom: -30px !important;
    }
    .ivu-form .ivu-form-item-label {
      color: #464c5b;
    }
  }
  .info {
    display: inline-block;
    width: 117px;
    margin-left: 24px;
    height: 72px;
    font-size: 12px;
    color: #464c5b;
    letter-spacing: 0;
    line-height: 18px;
    vertical-align: top;
  }
  .ivu-upload {
    width: 96px;
    height: 96px;
    position: relative;
    .replace_tit {
      position: absolute;
      bottom: 0;
      width: 96px;
      opacity: 0.6;
      background: #ed4014;
      height: 24px;
      text-align: center;
      line-height: 24px;
      font-size: 12px;
      color: #ffffff;
      display: none;
    }
    .replace_del {
      position: absolute;
      right: -15px;
      top: -9px;
      color: #fff;
      z-index: 1000;
      // display: none;
    }
  }
  .ivu-upload:hover .replace_tit {
    display: block;
  }
  .treeselect_box {
    display: flex;
    align-items: center;
    margin-left: 30px;
    padding-top: 24px;
    span {
      margin-right: 8px;
    }
  }
  .vue-treeselect__multi-value {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .vue-treeselect__multi-value-label {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    max-width: 80px;
  }
  .vue-treeselect__limit-tip {
    padding-top: 0px;
  }
  .vue-treeselect__multi-value-item-container {
    padding-top: 5px;
  }
  .vue-treeselect__multi-value-item {
    cursor: pointer;
    display: inline-table;
    background: #e3f2fd;
    padding: 0 0;
    border: 1px solid transparent;
    border-radius: 2px;
    color: #039be5;
    font-size: 12px;
    vertical-align: top;
  }
  .vue-treeselect__menu-container {
    width: 200px;
  }
  .tip-count{
    width: 280px;
    color: #c5c8ce;
    text-align: right;
  }
}
</style>
<style>
/* 多图上传样式 */
.characteristic {
  position: relative;
}
.characteristic_dec {
  position: absolute;
  bottom: 4px;
  right: 182px;
  font-size: 12px;
  display: inline-block;
  width: 31px;
  height: 14px;
  line-height: 14px;
  color: #c5c8ce;
}
.cityfoem .ivu-form-item-content {
  margin-left: 40px !important;
}
</style>
